package org.fnzn.biz;

import org.fnzn.common.MyMapper;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Field;
import java.util.List;

public abstract class BaseBiz<M extends MyMapper<T>, T> {
    @Autowired
    protected M mapper;
    public void setMapper(M mapper){
        this.mapper = mapper;
    }

    public T selectOne(T entity) {
    	dealEntity(entity);
        return mapper.selectOne(entity);
    }


    public T selectById(Object id) {
        return mapper.selectByPrimaryKey(id);
    }

    public List<T> selectList(T entity) {
    	dealEntity(entity);
        return mapper.select(entity);
    }


    public List<T> selectListAll() {
        return mapper.selectAll();
    }

    public Long selectCount(T entity) {
        return new Long(mapper.selectCount(entity));
    }


    public void insert(T entity) {
        mapper.insert(entity);
    }


    public void insertSelective(T entity) {
        mapper.insertSelective(entity);
    }


    public void delete(T entity) {
        mapper.delete(entity);
    }


    public void deleteById(Object id) {
        mapper.deleteByPrimaryKey(id);
    }
    
    

    public void updateById(T entity) {
        mapper.updateByPrimaryKey(entity);
    }


    public void updateSelectiveById(T entity) {
        mapper.updateByPrimaryKeySelective(entity);

    }
    public  List<T> selectByExample(Object example){
        return mapper.selectByExample(example);
    }
    public int selectCountByExample(Object example){
        return mapper.selectCountByExample(example);
    }
     
    /**
     * 实体属性值为空字符串时 设置该属性为null
     * @param o
     */
    @SuppressWarnings("unused")
	private void dealEntity(Object o){
    	Class<?> claz = o.getClass();
   	 	Field[] fields=claz.getDeclaredFields();
   	 	Field f=null;
   	 	for(int i=0;i<fields.length;i++){
   	 		try {
	   	 		if (fields[i].getType().getName().equals("java.lang.String")) {
	   	 			f = claz.getDeclaredField(fields[i].getName());
					f.setAccessible(true);
					if(f.get(o)!=null&&f.get(o).toString().trim().equals("")){
						f.set(o, null);
					}
	   	 		}
			} catch (Exception e) {
				e.printStackTrace();
			} 
   	 	}
    }
}
